package main
import (
	"encoding/json"
	"fmt"
)
type ArticleClass struct {
	Id   int             `json:"id"`
	PID  int             `json:"pid"`
	Name string          `json:"name"`
	List []*ArticleClass `json:"list,omitempty"`
}
func main() {
	test := `[{"id":1,"pid":0,"name":"a"},{"id":2,"pid":1,"name":"b"},{"id":3,"pid":1,"name":"c"},{"id":4,"pid":2,"name":"d"},{"id":5,"pid":2,"name":"e"}]`
	fmt.Println(test)
	var list []*ArticleClass // 假设已经赋值进去，从 数据库取出的数据
	if err := json.Unmarshal([]byte(test), &list); err != nil {
		return
	}
	//fmt.Println(list)
	data := buildData(list)
	dd, _ := json.Marshal(data)
	fmt.Println(string(dd))
	//fmt.Println(data)
	result := makeTreeCore(0, data)
	//fmt.Println("resule", result)
	temp, _ := json.Marshal(result)
	fmt.Println(string(temp))
}
func buildData(list []*ArticleClass) map[int]map[int]*ArticleClass {
	var data map[int]map[int]*ArticleClass = make(map[int]map[int]*ArticleClass)
	for _, v := range list {
		id := v.Id
		fid := v.PID
		if _, ok := data[fid]; !ok {
			data[fid] = make(map[int]*ArticleClass)
		}
		data[fid][id] = v
	}
	return data
}
func makeTreeCore(index int, data map[int]map[int]*ArticleClass) []*ArticleClass {
	tmp := make([]*ArticleClass, 0) // 等于var tmp []*ArticleClass

	for id, item := range data[index] {
		//fmt.Println(id, item)
		//fmt.Println(data[id])
		if data[id] != nil {
			item.List = makeTreeCore(id, data)
		}
		//fmt.Println(tmp)
		tmp = append(tmp, item)
	}
	return tmp
}